package com.cmsz.uregs.controllers;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cmsz.uregs.entity.User;
import com.cmsz.uregs.service.UserService;

@RestController
public class UserController {
	@Autowired
	private UserService userService;

	@RequestMapping(value = "user", method = RequestMethod.GET)
	public List<User> findAllUsers() {
		return userService.findAllUsers();
	}

	@RequestMapping(value = "user/{username}", method = RequestMethod.GET)
	public User findUserByUsername(@PathVariable String username) {
		return userService.findUserByName(username);
	}

	@RequestMapping(value = "user/{username}/{password}", method = RequestMethod.GET)
	public String findUser(@PathVariable String username, @PathVariable String password, HttpSession session) {
		User realUser = userService.findUserByName(username);
		if (realUser != null && realUser.getPassword().equals(password)) {
			session.setAttribute("username", realUser.getUsername());
			return "success";
		}
		return "用户名密码不正确";
	}

	@RequestMapping(value = "user", method = RequestMethod.POST)
	public String addUser(@RequestBody User user) {
		if (userService.findUserByName(user.getUsername()) != null) {
			return "用户名已存在";
		}
		userService.addUser(user);
		return "success";
	}

	@RequestMapping(value = "user", method = RequestMethod.PUT)
	public String updateUser(@RequestBody User user) {
		userService.updateUser(user);

		return "success";
	}

	@RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
	public void deleteUser(@PathVariable int id) {
		userService.deleteUser(id);
	}
}
